package com.fs.cv.controller;

import com.fs.cv.dao.ImageDao;
import com.fs.cv.pojo.pojodao.*;
import com.fs.cv.service.RoleService;
import com.fs.cv.service.UserService;
import org.apache.shiro.SecurityUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;


import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 类：user相关业务
 *
 * @author 周先华
 * @date 2020/10/3
 */

@RequestMapping("/user")
@Controller
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    RoleService roleService;
    @Autowired
    ImageDao imageDao;

    /**
     * 方法描述:查询用户信息
     *
     * @param
     * @return java.util.Map<java.lang.String, java.lang.Object>
     * @author 周先华
     * @date 2020/10/4
     */
    @RequestMapping("/queryAllUsers")
    @ResponseBody
    public Map<String, Object> queryAllUsers(Integer currentPage, Integer pageSize) {
        Map<String, Object> result = new HashMap<>();
        //获取用户角色信息
        PageInfo<User> pageInfo =userService.getUsersByPage(currentPage,pageSize);
        result.put("code", 0);
        result.put("message", "获取用户数据成功");
        result.put("totalPage", pageInfo.getPages());
        result.put("userList", pageInfo.getList());
        return result;

    }

    @ResponseBody
    @RequestMapping("/getOneUserInfo")
    public Map<String, Object> getOneUserInfo(User user) {
        //前端传递，自动封装成对象，需要注意
        Map<String, Object> result = new HashMap<>();
        //查询角色信息权限信息
        Role role = roleService.queryRoleInfoByUserId(user.getUserId());
        result.put("role", role);

        //判断角色类型
        //后端进行对应的查询
        //查询角色对应的信息
        //后端代码不能有任何错误，否则会报ajax错误
        switch (role.getName()) {
            case "任课教师":
                Teacher teacher = userService.queryTeacherInfoByUserId(user.getUserId());
                result.put("teacher", teacher);
                break;
            case "班主任":
                Headmaster headmaster = userService.queryHeadmasterInfoByUserId(user.getUserId());
                result.put("headmaster", headmaster);
                break;
            case "教务主任":
                Registrar registrar = userService.queryRegistrarInfoByUserId(user.getUserId());
                System.out.println(registrar);
                result.put("registrar",registrar);
                break;
            case "管理员":
                result.put("message", "你是尊贵的管理员用户");
                break;
            case "学生":

                break;
        }

        return result;
    }


    @RequestMapping("/edit")
    @ResponseBody
    public Map<String, Object> editUserInfo( User user,  Role role,  Teacher teacher,  Headmaster headmaster,  Registrar registrar) {
        Map<String, Object> result = new HashMap<>();
      boolean userFlag = userService.addUserInfo(user,role,teacher,headmaster,registrar);
        if (userFlag) {
            //添加成功
            result.put("code",1);
        }else {
            //添加失败
            result.put("code",-1);
        }
        return result;
    }

    @RequestMapping("/changeDeleted")
    @ResponseBody
    public Map<String, Object> changeUserDeleted(User user) {
        boolean userFlag=userService.changeUserDeleted(user);
        Map<String, Object>result = new HashMap<>();
        if (userFlag) {
            //修改成功
            result.put("code",1);
        }else {
            //修改失败
            result.put("code",-1);
        }
        return result;
    }

    @RequestMapping("/getUserInfoByUserId")
    @ResponseBody
    public Map<String,Object> getUserInfoByUserId(User user){
        Map<String, Object>result = new HashMap<>();
        User user1 =userService.getUserInfoByUserId(user.getUserId());
        result.put("user",user1);
        return result;
    }


    @RequestMapping("/editUserInfoAjax")
    @ResponseBody
    public Map<String,Object> editUserInfoAjax(User user) {
        Map<String, Object>result = new HashMap<>();
        boolean updataFlag=userService.updataUserInfo(user);
        if (updataFlag) {
            //修改成功
            result.put("code",1);
        }else {
            //修改失败
            result.put("code",-1);
        }
        return result;
    }

    /**
     * 上传头像
     * @param headImage
     * @param request
     * @return
     */
    @RequestMapping("/uploadHeadImage")
    @ResponseBody
    @Transactional
    public Map<String,Object> uploadHeadImage(MultipartFile headImage, MultipartHttpServletRequest request) {
        Map<String, Object>result = new HashMap<>();
        if(headImage!=null) {
            User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
            String path="WEB-INF/static/upload/";
            String realPath=request.getServletContext().getRealPath(path);
            String name=headImage.getOriginalFilename();
            String ext=name.substring(name.indexOf('.'));
            //查询以前的头像
            Map<String,Object> mapOld=imageDao.selectImage(user.getUserId());
            //准备插入或者更新的数据
            Map<String,Object> map=new HashMap<>();
            String prefix=String.valueOf(System.currentTimeMillis());
            map.put("user_id",user.getUserId());
            map.put("image_name", prefix+ext);
            if(mapOld==null) {
                //以前没有头像
                imageDao.insertImage(map);
                realPath += map.get("image_name");
            }else{
                //有头像，先删除老的
                String oldRealPath=realPath+mapOld.get("image_name");
                System.out.println(oldRealPath);
                boolean delete = new File(oldRealPath).delete();
                System.out.println(delete);
                //更新为新的
                imageDao.updateImage(map);
                realPath += map.get("image_name");
            }
            System.out.println(realPath);
            try {
                File file = new File(realPath);
                if (!file.getParentFile().exists()&&!file.isDirectory()){
                    file.getParentFile().mkdirs();
                    file.createNewFile();
                } else {
                    file.createNewFile();
                }
                headImage.transferTo(file);
            }catch (IOException e){
                e.printStackTrace();
            }
            result.put("code",0);
        }else result.put("code",-1);
        return result;
    }

    /**
     * 获取头像
     * @return
     */
    @RequestMapping("/getHeadImage")
    public String getHeadImage() {
        User user = (User) SecurityUtils.getSubject().getSession().getAttribute("user");
        System.out.println(user);
        Map<String, Object> map = imageDao.selectImage(user.getUserId());
        String imageStr = "";
        if (map == null) imageStr = "/static/img/user.png";
        else imageStr = "/static/upload/" + map.get("image_name");
        return "redirect:" + imageStr;
    }

    @RequestMapping("/getFreeCourseId")
    @ResponseBody
    public Map<String,Object> getFreeCourseId(){
        Map<String, Object>result = new HashMap<>();
      List<Course> surplusCourse= userService.getFreeCourseId();
       result.put("code",0);
       result.put("surplusCourse",surplusCourse);
       return result;
    }
}
